<template>
  <div id="knowManageApprovalDiv">
    <Breadcrumb content="知识库审核" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="20">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findContentApprovalTree"></vxe-button>
            </template>
          </vxe-toolbar>

          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="contentApprovalTree" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree"
                @node-click="handleClickType" v-loading="treeloading">
                <template #default="{ data }">
                  <span><img :src="'../../../src/assets/images/Knowledge/' + data.knType + '.png'" style="width: 15px; height: 15px; margin-right: 10px" />
                    <div style="float: right">
                      {{ data.name }}
                    </div>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-scrollbar>
        </Pane>
        <Pane size="75">
          <div class="cardBox" v-loading="conloading" element-loading-text="富文本加载中，请耐心等待..." element-loading-spinner="el-icon-loading">
            <!-- <el-scrollbar style="height: 100%"> -->
            <div class="item-interval" v-if="!isEmpty(sltContent)">
              <el-divider content-position="left" class="el-divider-title">
                {{ sltContent.title }}
                <vxe-button type="text" status="primary" icon="vxe-icon-send" v-if="sltContent.status == 5 || sltContent.status == 15" content="审核" @click="approvalContent"></vxe-button>
              </el-divider>
              <CkEditor ref="refContentCkEditor" :folderId="sltCatalogData.id" @editor-input="(val) => (sltContent.tempContent = val)" />

              <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
                <el-tab-pane label="问题" name="issueTab">
                  <div class="tabTableBox">
                    <vxe-table :data="sltContent.wkKnowledgeIssueList" class="mytable-scrollbar" height="auto">
                      <vxe-column type="seq" title="序号" width="60"></vxe-column>
                      <vxe-column field="title" title="问题">
                        <template #default="{ row }">
                          {{ row.title }}

                          <el-popover placement="right" :width="200" trigger="hover">
                            <div v-html="row.solution"></div>
                            <template #reference>
                              <el-button icon="view" size="mini" type="text" style="margin-left: 10px">查看解决方案</el-button>
                            </template>
                          </el-popover>
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="审核记录" name="approvalTab">
                  <el-scrollbar>
                    <KnowledgeApprovalList ref="approvalListRef" />
                  </el-scrollbar>
                </el-tab-pane>
              </el-tabs>
            </div>
            <!-- </el-scrollbar> -->
          </div>
        </Pane>
      </Splitpanes>
    </div>

    <el-dialog title="审核" width="800px" :show-close="false" :draggable="true" v-model="showApprovalDialog" :append-to-body="true" :close-on-click-modal="false">
      <el-form ref="approvalFormRef" :model="approvalForm" label-width="80px" class="form-input-l" :inline-message="true">
        <el-form-item prop="content" label="修改前">
          <CkEditor ref="contentCkEditorRef" :folderId="sltContent.id" @editor-input="(val) => (approvalForm.content = val)" style="width: 700px" />
        </el-form-item>

        <el-form-item prop="tempContent" label="修改后">
          <CkEditor ref="refTempContentCkEditor" :folderId="sltContent.id" @editor-input="(val) => (approvalForm.tempContent = val)" style="width: 700px" />
        </el-form-item>
        <el-form-item prop="solution" label="审批意见">
          <el-input v-model="approvalForm.approvalReason" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex justify-end">
        <el-button type="info" @click="rejectApproval('approvalFormRef')">驳回</el-button>
        <el-button type="primary" @click="consentApproval('approvalFormRef')">通过</el-button>
        <el-button @click="closeApprovalDialog('approvalFormRef')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '@/stores/store';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import CkEditor from '@/components/CkEditor.vue';
import KnowledgeApprovalList from './KnowledgeApprovalList.vue'; //失控记录图表

let store = AppStore();

let treeloading = ref(false); //字典分类树上的刷新
let conloading = ref(false);

let showApprovalDialog = ref(false);
let sltContent: any = ref({});
let sltCatalogData: any = {};
let activeName = ref('issueTab');
let contentApprovalTree: any = reactive([]); //最左侧质控靶值设定树数据
let approvalListRef: any = ref(null);
let approvalForm = reactive({
  id: null,
  contentId: '',
  submitter: '',
  submitTime: '',
  submitReason: '',
  approvalor: '',
  approvalTime: '',
  approvalReason: '',
  tempContent: '',
  orgId: '',
  classify: '',
  status: 0
});

onMounted(() => {
  findContentApprovalTree(); // 获取质控规则表格数据
});

function findContentApprovalTree() {
  treeloading.value = true;
  contentApprovalTree.length = 0;
  const url = '/api/wk/wkKnowledgeApproval/findContentApprovalTree';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      contentApprovalTree.push(...res.data);
      if (contentApprovalTree.length > 0) {
        const sltObj = getChildren(contentApprovalTree[0]);
        sltCatalogData = sltObj;
        setCurTypeNode(sltObj.id);
        if (sltCatalogData.knType == 'content') {
          getContentByContentId();
        } else {
          sltContent.value = {};
        }
      } else {
        sltCatalogData = {};
        sltContent.value = {};
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取数据异常', VxeNotifyType.error);
    });
}

//点击左侧分类
function handleClickType(obj: any) {
  sltCatalogData = obj;
  if (sltCatalogData.knType == 'content') {
    getContentByContentId();
  } else {
    sltContent.value = {};
  }
}
function getContentByContentId() {
  conloading.value = true;

  if (isEmpty(sltCatalogData)) {
    conloading.value = false;
    return;
  }
  const url = '/api/wk/wkKnowledgeApproval/getContentAndApprovaByContentId';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { contentId: sltCatalogData.id } })
    .then((res: any) => {
      sltContent.value = res.data;
      proxy.$nextTick(() => {
        const temp: any = proxy.$refs['refContentCkEditor'];
        temp.editorDisabled = true;
        //if (sltContent.value.status < 10) {
        if (isEmpty(sltContent.value.tempContent)) {
          temp.setValue('');
        } else {
          temp.setValue(sltContent.value.tempContent);
        }
        // } else {
        //   if (isEmpty(sltContent.value.content)) {
        //     temp.setValue('');
        //   } else {
        //     temp.setValue(sltContent.value.content);
        //   }
        // }
        if (activeName.value == 'approvalTab') {
          console.log(approvalListRef);
          approvalListRef.value.initPage(sltContent.value.id);
        }
      });
      conloading.value = false;
    })
    .catch((err: any) => {
      conloading.value = false;
      console.log(err);

      VxeMessage('获取数据异常', VxeNotifyType.error);
    });
}

function approvalContent() {
  approvalForm.contentId = sltContent.value.approval.contentId;
  approvalForm.id = sltContent.value.approval.id;
  approvalForm.contentId = sltContent.value.approval.contentId;
  approvalForm.submitter = sltContent.value.approval.submitter;
  approvalForm.submitTime = sltContent.value.approval.submitTime;
  approvalForm.submitReason = sltContent.value.approval.submitReason;
  approvalForm.approvalor = sltContent.value.approval.approvalor;
  approvalForm.approvalTime = sltContent.value.approval.approvalTime;
  approvalForm.approvalReason = sltContent.value.approval.approvalReason;
  approvalForm.tempContent = sltContent.value.tempContent;
  approvalForm.orgId = sltContent.value.approval.orgId;
  approvalForm.classify = sltContent.value.approval.classify;
  approvalForm.status = sltContent.value.approval.status;

  showApprovalDialog.value = true;
  proxy.$nextTick(() => {
    const tempt: any = proxy.$refs['refTempContentCkEditor'];
    if (isEmpty(sltContent.value.tempContent)) {
      tempt.setValue('');
    } else {
      tempt.setValue(sltContent.value.tempContent);
    }
    const temp: any = proxy.$refs['contentCkEditorRef'];
    if (isEmpty(sltContent.value.content)) {
      temp.setValue('');
    } else {
      temp.setValue(sltContent.value.content);
    }
  });
}

function rejectApproval() {
  submitApproval(5);
}

function consentApproval() {
  submitApproval(10);
}
function submitApproval(status: any) {
  proxy
    .$confirm('确定审核?', '提示', {
      cancelButtonClass: 'cancelbutton',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const obj = {
        id: approvalForm.id,
        contentId: approvalForm.contentId,
        approvalor: store.userInfo.id,
        approvalReason: approvalForm.approvalReason,
        tempContent: approvalForm.tempContent,
        status: status
      };
      const url = '/api/wk/wkKnowledgeApproval/submitApproval';

      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          if (res.status.code === 1) {
            showApprovalDialog.value = false;
            // 清空表单
            clearApprovalForm();
            findContentApprovalTree();
          } else {
            VxeMessage('审批失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('保存异常', VxeNotifyType.error);
          console.log(err);
        });
    })
    .catch((err) => {
      console.log(err);
    });
}

function closeApprovalDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearApprovalForm();
  showApprovalDialog.value = false;
}

function clearApprovalForm() {
  approvalForm.id = null;
  approvalForm.contentId = '';
  approvalForm.submitter = '';
  approvalForm.submitTime = '';
  approvalForm.submitReason = '';
  approvalForm.approvalor = '';
  approvalForm.approvalTime = '';
  approvalForm.approvalReason = '';
  approvalForm.orgId = '';
  approvalForm.classify = '';
  approvalForm.status = 0;
}
function getChildren(obj: any) {
  const children = obj.children;
  if (children.length > 0) {
    return getChildren(children[0]);
  } else {
    return obj;
  }
}

function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

function tabHandleClick(tab) {
  if (tab.index == 1) {
    approvalListRef.value.initPage(sltContent.value.id);
  }
}
</script>

<style lang="scss" scoped>
#knowManageApprovalDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .cardBox {
        height: 100%;
        .item-interval {
          height: 100%;
          .el-tabs {
            height: calc(100% - 342px - 50px);
            :deep(.el-tabs__content) {
              height: calc(100% - 39px);
              padding: 0;
              .el-tab-pane {
                height: 100%;
                .tabTableBox {
                  height: 100%;
                }
                .timelineBox {
                  height: 100%;
                  padding: 0 10px 0 0;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
